var Partners = require("../models/_partners");

// 轮播管理
exports.getPartners = function(callback){
    Partners.find().sort({sort:"asc"}).exec(function (err, _partnersList) {
        if (err) {
            return callback(err)
        } else {
            return callback(null, _partnersList)
        }
    });
}

//合作伙伴列表
exports.partnersList = function (req, res) {
    var pageSize = 20; //每页显示条数
    var page = req.params.num - 1 || 0;
    Partners.find().count().exec(function (err, sum) {
        Partners.find().limit(pageSize).skip(pageSize*page).sort({sort:"asc"}).exec(function (err,banner) {
            res.render('admin/partnersList', {
                title: '合作伙伴列表',
                banner: banner,
                pagesize: sum
            })
        });
    });
}
//添加轮播
exports.partnersAdd = function (req, res) {
    res.render("admin/partnersAdd", {
        title: "添加合作伙伴"
    });
}

//更新合作伙伴
exports.partnersUpdate = function (req, res) {
    var id = req.params.id;
    Partners.findOne({"_id":id},function (err, banner) {
        if (err) {
            console.log(err)
        }else {
            res.render("admin/partnersUpdate", {
                title: "编辑合作伙伴",
                partners:banner
            });
        }

    });
}

//保存、编辑
exports.partnersSave = function (req, res) {
    var $partners = req.body;
    var id = $partners._id;
    if (id) {
        Partners.update({
            _id: id
        }, $partners, function (err, _partnersList) {
            if(err){
                console.log(err)
            }
            res.send({
                "success":true,
                "partnersList":_partnersList,
                "msg":"更新成功"
            })
        });
    } else {
        delete $partners._id
        Partners.create($partners, function (err, _partnersList) {
            if(err){
                console.log(err)
            }
            res.send({
                "success":true,
                "partnersList":_partnersList,
                "msg":"提交成功"
            })
        });
    }
}

exports.partnersDelete = function (req, res) {
    var id = req.params.id;
    Partners.remove({
        _id: id
    }, function (err) {
        res.redirect("/admin/partnersList");
    })
}